package kuzmenkov.applet;

import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Logger;

/**
 * The class listens mouse events of image components
 * 
 * @author Michael Kuzmenkov
 * 
 */
public class ImageMouseListener extends MouseAdapter {

	private Logger log = Logger.getLogger(this.getClass().getPackage().getName());

	private ViewerApplet viewerApplet;

	public ImageMouseListener(ViewerApplet viewerApplet) {
		if (viewerApplet == null)
			throw new IllegalArgumentException("The argument viewerApplet is null");
		this.viewerApplet = viewerApplet;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		Object source = e.getSource();
		if (source == null || !(source instanceof TitledImageComp)) {
			log
					.warning("The unexpected type of the source or the source is null");
			return;
		}
		TitledImageComp imComp = (TitledImageComp) source;
		viewerApplet.setCurrImageComp(imComp);

		int button = e.getButton();
		if (button == MouseEvent.BUTTON1)
			leftButtonClicked(e, imComp);
		else if (button == MouseEvent.BUTTON2 || button == MouseEvent.BUTTON3)
			rightButtonClicked(e, imComp);

	}

	private void leftButtonClicked(MouseEvent e, TitledImageComp imComp) {
		Image image = imComp.getImage();
		String title = imComp.getTitle();

		ImageDlg imageDlg = viewerApplet.getImageDlg();
		imageDlg.setImage(image);
		imageDlg.setTitle(title);
		if (imageDlg.getWidth() <= imComp.getWidth()
				&& imageDlg.getHeight() <= imComp.getHeight()) {
			log.fine("The ImageDlg was not appeared "
					+ "because of the size of the image");
			return;
		}

		Point compLoc = imComp.getLocationOnScreen();
		int x = (int) compLoc.getX()
				- (imageDlg.getWidth() - imComp.getWidth()) / 2;
		int y = (int) compLoc.getY()
				- (imageDlg.getHeight() - imComp.getHeight()) / 2;
		Point dlgLoc = new Point(x, y);

		imageDlg.setLocation(dlgLoc);
		imageDlg.setVisible(true);

	}

	private void rightButtonClicked(MouseEvent e, TitledImageComp imComp) {
		viewerApplet.getPopup().show(imComp, e.getX(), e.getY());
	}

}
